// 存储测试信息的对象
let testData = {
  scripts: [],
  runningScript: null,
  isRunning: false
};

// 监听来自侧边栏的消息
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  console.log('后台脚本收到消息:', message);
  
  if (message.action === 'run_script') {
    // 执行测试脚本
    console.log("准备执行脚本:", message.script);
    executeScript(message.script, message.params)
      .then(result => {
        sendResponse({ success: true, result });
      })
      .catch(error => {
        console.error("执行脚本失败:", error);
        sendResponse({ success: false, error: error.message });
      });
    return true; // 异步响应
  }
  
  if (message.action === 'save_script') {
    // 保存测试脚本
    saveScript(message.script)
      .then(() => {
        sendResponse({ success: true });
      })
      .catch(error => {
        sendResponse({ success: false, error: error.message });
      });
    return true; // 异步响应
  }
  
  if (message.action === 'get_scripts') {
    // 获取所有保存的脚本
    getScripts().then(scripts => {
      sendResponse({ success: true, scripts });
    });
    return true; // 异步响应
  }
  
  if (message.action === 'stop_script') {
    // 停止正在运行的脚本
    stopScript();
    sendResponse({ success: true });
  }
});

// 保存脚本
async function saveScript(script) {
  // 确保脚本有唯一ID
  if (!script.id) {
    script.id = Date.now().toString();
    script.createdAt = new Date().toISOString();
  }
  script.updatedAt = new Date().toISOString();
  
  // 从存储中获取现有脚本
  const data = await chrome.storage.local.get('testScripts');
  let scripts = data.testScripts || [];
  
  // 检查是否已存在此脚本，如果是则更新，否则添加新的
  const existingIndex = scripts.findIndex(s => s.id === script.id);
  if (existingIndex >= 0) {
    scripts[existingIndex] = script;
  } else {
    scripts.push(script);
  }
  
  // 保存更新后的脚本列表
  await chrome.storage.local.set({ testScripts: scripts });
  testData.scripts = scripts;
  
  return script;
}

// 获取所有保存的脚本
async function getScripts() {
  const data = await chrome.storage.local.get('testScripts');
  testData.scripts = data.testScripts || [];
  return testData.scripts;
}

// 执行测试脚本
async function executeScript(script, params) {
  if (testData.isRunning) {
    throw new Error("已有脚本正在运行，请先停止它");
  }
  
  testData.isRunning = true;
  testData.runningScript = script;
  
  try {
    // 通知侧边栏脚本开始执行
    chrome.runtime.sendMessage({
      type: 'script_status',
      status: 'running',
      scriptId: script.id,
      message: `开始执行脚本: ${script.name}`
    });
    
    // 解析并执行脚本步骤
    const steps = script.steps;
    const results = [];
    
    for (let i = 0; i < steps.length; i++) {
      const step = steps[i];
      // 替换步骤中的参数占位符
      const processedStep = processStepWithParams(step, params);
      
      // 通知侧边栏当前步骤
      chrome.runtime.sendMessage({
        type: 'script_step',
        stepIndex: i,
        totalSteps: steps.length,
        stepInfo: processedStep
      });
      
      // 执行步骤并获取结果
      const result = await executeStep(processedStep);
      results.push(result);
      
      if (result.success === false) {
        throw new Error(`步骤 ${i + 1} 失败: ${result.error}`);
      }
      
      // 步骤之间的延迟
      if (i < steps.length - 1 && processedStep.delay) {
        await new Promise(resolve => setTimeout(resolve, processedStep.delay));
      }
      
      // 检查是否停止执行
      if (!testData.isRunning) {
        throw new Error("脚本执行被用户手动停止");
      }
    }
    
    // 通知侧边栏脚本执行完成
    chrome.runtime.sendMessage({
      type: 'script_status',
      status: 'completed',
      scriptId: script.id,
      results: results
    });
    
    testData.isRunning = false;
    testData.runningScript = null;
    
    return { success: true, results };
  } catch (error) {
    // 通知侧边栏脚本执行失败
    chrome.runtime.sendMessage({
      type: 'script_status',
      status: 'error',
      scriptId: script.id,
      error: error.message
    });
    
    testData.isRunning = false;
    testData.runningScript = null;
    
    throw error;
  }
}

// 停止脚本执行
function stopScript() {
  if (testData.isRunning) {
    testData.isRunning = false;
    chrome.runtime.sendMessage({
      type: 'script_status',
      status: 'stopped',
      scriptId: testData.runningScript?.id,
      message: "脚本执行已手动停止"
    });
  }
}

// 处理步骤中的参数
function processStepWithParams(step, params) {
  if (!params) return step;
  
  const processedStep = JSON.parse(JSON.stringify(step));
  
  // 替换操作参数中的变量
  if (processedStep.args) {
    for (const key in processedStep.args) {
      if (typeof processedStep.args[key] === 'string') {
        processedStep.args[key] = processedStep.args[key].replace(/\${([^}]+)}/g, (match, paramName) => {
          return params[paramName] !== undefined ? params[paramName] : match;
        });
      }
    }
  }
  
  return processedStep;
}

// 执行单个操作步骤
async function executeStep(step) {
  console.log(`执行步骤: ${step.action}，参数:`, step.args);
  
  try {
    switch(step.action) {
      case 'navigate_to_url':
        return await navigateToUrl(step.args?.url);
        
      case 'click':
        return await clickElement(step.args?.selector);
        
      case 'wait':
        return await wait(step.args?.milliseconds);
        
      case 'input':
        return await inputText(step.args?.selector, step.args?.text);
        
      case 'extract':
        return await extractContent(step.args?.selector);
        
      case 'execute_js':
        return await executeJs(step.args?.code);
        
      case 'screenshot':
        return await takeScreenshot();
        
      default:
        throw new Error(`未知的操作类型: ${step.action}`);
    }
  } catch (error) {
    console.error(`执行步骤失败: ${step.action}`, error);
    return { success: false, action: step.action, error: error.message };
  }
}

// 导航到指定URL
async function navigateToUrl(url) {
  if (!url) throw new Error("缺少URL参数");
  
  try {
    const tab = await chrome.tabs.create({ url });
    // 等待页面加载完成
    await new Promise(resolve => {
      function listener(tabId, changeInfo) {
        if (tabId === tab.id && changeInfo.status === 'complete') {
          chrome.tabs.onUpdated.removeListener(listener);
          resolve();
        }
      }
      chrome.tabs.onUpdated.addListener(listener);
    });
    
    return {
      success: true,
      action: 'navigate_to_url',
      url: url,
      tabId: tab.id
    };
  } catch (error) {
    throw new Error(`导航到 ${url} 失败: ${error.message}`);
  }
}

// 点击元素
async function clickElement(selector) {
  if (!selector) throw new Error("缺少选择器参数");
  
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab) throw new Error("没有找到活动标签页");
  
  const results = await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: (cssSelector) => {
      const element = document.querySelector(cssSelector);
      if (!element) {
        return { success: false, error: `没有找到元素: ${cssSelector}` };
      }
      
      // 滚动到元素可见
      element.scrollIntoView({ behavior: "smooth", block: "center" });
      
      // 模拟点击
      element.click();
      return { 
        success: true, 
        element: {
          tagName: element.tagName,
          id: element.id,
          className: element.className
        }
      };
    },
    args: [selector]
  });
  
  const result = results[0].result;
  if (!result.success) {
    throw new Error(result.error);
  }
  
  return {
    success: true,
    action: 'click',
    selector: selector,
    elementInfo: result.element
  };
}

// 等待指定毫秒数
async function wait(milliseconds) {
  if (!milliseconds || isNaN(milliseconds)) {
    milliseconds = 1000; // 默认等待1秒
  }
  
  await new Promise(resolve => setTimeout(resolve, parseInt(milliseconds)));
  
  return {
    success: true,
    action: 'wait',
    milliseconds: milliseconds
  };
}

// 在输入框中输入文本
async function inputText(selector, text) {
  if (!selector) throw new Error("缺少选择器参数");
  if (text === undefined) throw new Error("缺少文本参数");
  
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab) throw new Error("没有找到活动标签页");
  
  const results = await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: (cssSelector, inputText) => {
      const element = document.querySelector(cssSelector);
      if (!element) {
        return { success: false, error: `没有找到元素: ${cssSelector}` };
      }
      
      // 检查元素是否可以接受输入
      if (!(element instanceof HTMLInputElement) && 
          !(element instanceof HTMLTextAreaElement) &&
          element.isContentEditable !== true) {
        return { success: false, error: `元素不是可输入类型: ${element.tagName}` };
      }
      
      // 聚焦元素
      element.focus();
      
      // 根据元素类型设置值
      if (element.isContentEditable) {
        element.textContent = inputText;
      } else {
        element.value = inputText;
        
        // 触发input和change事件
        element.dispatchEvent(new Event('input', { bubbles: true }));
        element.dispatchEvent(new Event('change', { bubbles: true }));
      }
      
      return { 
        success: true,
        element: {
          tagName: element.tagName,
          id: element.id,
          className: element.className
        }
      };
    },
    args: [selector, text]
  });
  
  const result = results[0].result;
  if (!result.success) {
    throw new Error(result.error);
  }
  
  return {
    success: true,
    action: 'input',
    selector: selector,
    text: text,
    elementInfo: result.element
  };
}

// 提取元素内容
async function extractContent(selector) {
  if (!selector) throw new Error("缺少选择器参数");
  
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab) throw new Error("没有找到活动标签页");
  
  const results = await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: (cssSelector) => {
      const elements = document.querySelectorAll(cssSelector);
      if (elements.length === 0) {
        return { success: false, error: `没有找到元素: ${cssSelector}` };
      }
      
      const extractedData = Array.from(elements).map(el => ({
        text: el.textContent.trim(),
        html: el.innerHTML,
        tagName: el.tagName,
        attributes: Array.from(el.attributes).reduce((acc, attr) => {
          acc[attr.name] = attr.value;
          return acc;
        }, {})
      }));
      
      return { 
        success: true,
        count: elements.length,
        data: extractedData
      };
    },
    args: [selector]
  });
  
  const result = results[0].result;
  if (!result.success) {
    throw new Error(result.error);
  }
  
  return {
    success: true,
    action: 'extract',
    selector: selector,
    count: result.count,
    data: result.data
  };
}

// 执行自定义JavaScript代码
async function executeJs(code) {
  if (!code) throw new Error("缺少JavaScript代码");
  
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab) throw new Error("没有找到活动标签页");
  
  try {
    // 将代码字符串转换为实际函数
    const functionCode = `(function() { 
      try {
        ${code}
        return { success: true };
      } catch (error) {
        return { success: false, error: error.message };
      }
    })()`;
    
    const results = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: new Function('return ' + functionCode)
    });
    
    const result = results[0].result;
    if (!result.success) {
      throw new Error(`脚本执行错误: ${result.error}`);
    }
    
    return {
      success: true,
      action: 'execute_js',
      result: result
    };
  } catch (error) {
    throw new Error(`执行JavaScript代码失败: ${error.message}`);
  }
}

// 截取当前页面屏幕截图
async function takeScreenshot() {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab) throw new Error("没有找到活动标签页");
    
    const dataUrl = await chrome.tabs.captureVisibleTab();
    
    // 发送截图数据到侧边栏
    chrome.runtime.sendMessage({
      type: 'screenshot',
      dataUrl: dataUrl,
      timestamp: Date.now()
    });
    
    return {
      success: true,
      action: 'screenshot',
      timestamp: Date.now()
    };
  } catch (error) {
    throw new Error(`截图失败: ${error.message}`);
  }
}

// 导入示例脚本
import { sampleScripts, loadSampleScripts } from './samples.js';

// 初始化时从存储中加载数据
chrome.runtime.onInstalled.addListener(async function() {
  const data = await chrome.storage.local.get('testScripts');
  if (data.testScripts) {
    testData.scripts = data.testScripts;
    console.log('已从存储加载测试脚本:', testData.scripts);
  } else {
    console.log('未找到存储的测试脚本，使用默认值');
  }
  
  // 设置侧边栏默认启用
  chrome.sidePanel.setOptions({
    enabled: true,
    path: 'panel.html'
  });
  
  // 加载示例脚本
  loadSampleScripts();
  
  console.log('浏览器自动化测试工具已安装/更新');
});

// 当扩展图标被点击时，打开侧边栏
chrome.action.onClicked.addListener((tab) => {
  chrome.sidePanel.open({ tabId: tab.id });
}); 